package com.hub.transform;

import com.hub.entity.MySensor;
import com.hub.entity.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class TransformRichFromCustom {

    public static void main(String[] args) throws Exception {

        // 环境准备
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();

        // 添加数据源：自定义数据源
        DataStreamSource<SensorReading> dataStreamSource = executionEnvironment.addSource(new MySensor());


        // 分组
        KeyedStream<SensorReading, String> sensorReadingStringKeyedStream = dataStreamSource.keyBy(SensorReading::getId);

        SingleOutputStreamOperator<SensorReading> reduce = sensorReadingStringKeyedStream.reduce((o1, o2) -> {
                                                                if (o1.getTemplate() > o2.getTemplate()) {
                                                                    return o1;
                                                                }
                                                                if (o1.getTime() > o2.getTime()) {
                                                                    return o1;
                                                                }
                                                                if (o1.getId().compareTo(o2.getId()) > 0) {
                                                                    return o1;
                                                                }
                                                                return o2;
                                                            });

        // 打印任务
        reduce.print("reduce_from_custom");

        // 执行
        executionEnvironment.execute();


    }
}
